<?php
class Purchase_Order_Item extends QDB_ActiveRecord_Abstract
{
	/**
	 * 返回对象的定义
	 *
	 * @static
	 *
	 * @return array
	 */
	static function __define()
	{
		return array
		(
			// 指定该 ActiveRecord 要使用的行为插件
			'behaviors' => '',

			// 指定行为插件的配置
			'behaviors_settings' => array
			(
				# '插件名' => array('选项' => 设置),
			),

			// 用什么数据表保存对象
			'table_name' => 'purchase_order_item',

			// 指定数据表记录字段与对象属性之间的映射关系
			// 没有在此处指定的属性，QeePHP 会自动设置将属性映射为对象的可读写属性
			'props' => array
			(
				// 主键应该是只读，确保领域对象的“不变量”
				'id' => array('readonly' => true),

				/**
				 *  可以在此添加其他属性的设置
				 */
				# 'other_prop' => array('readonly' => true),

				/**
				 * 添加对象间的关联
				 */
				# 'other' => array('has_one' => 'Class'),

			),

			/**
			 * 允许使用 mass-assignment 方式赋值的属性
			 *
			 * 如果指定了 attr_accessible，则忽略 attr_protected 的设置。
			 */
			'attr_accessible' => '',

			/**
			 * 拒绝使用 mass-assignment 方式赋值的属性
			 */
			'attr_protected' => 'id',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值不允许由外部提供
			 *
			 * 这里指定的属性会在创建记录时被过滤掉，从而让数据库自行填充值。
			 */
			'create_reject' => '',

			/**
			 * 指定更新数据库中的对象时，哪些属性的值不允许由外部提供
			 */
			'update_reject' => '',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 如果填充值为 self::AUTOFILL_TIMESTAMP 或 self::AUTOFILL_DATETIME，
			 * 则会根据属性的类型来自动填充当前时间（整数或字符串）。
			 *
			 * 如果填充值为一个数组，则假定为 callback 方法。
			 */
			'create_autofill' => array
			(
				# 属性名 => 填充值
				# 'is_locked' => 0,
			),

			/**
			 * 指定更新数据库中的对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 填充值的指定规则同 create_autofill
			 */
			'update_autofill' => array
			(
			),

			/**
			 * 在保存对象时，会按照下面指定的验证规则进行验证。验证失败会抛出异常。
			 *
			 * 除了在保存时自动验证，还可以通过对象的 ::meta()->validate() 方法对数组数据进行验证。
			 *
			 * 如果需要添加一个自定义验证，应该写成
			 *
			 * 'title' => array(
			 *	array(array(__CLASS__, 'checkTitle'), '标题不能为空'),
			 * )
			 *
			 * 然后在该类中添加 checkTitle() 方法。函数原型如下：
			 *
			 * static function checkTitle($title)
			 *
			 * 该方法返回 true 表示通过验证。
			 */
			'validations' => array
			(
			),
		);
	}


/* ------------------ 以下是自动生成的代码，不能修改 ------------------ */

	/**
	 * 开启一个查询，查找符合条件的对象或对象集合
	 *
	 * @static
	 *
	 * @return QDB_Select
	 */
	static function find()
	{
		$args = func_get_args();
		return QDB_ActiveRecord_Meta::instance(__CLASS__)->findByArgs($args);
	}

	/**
	 * 返回当前 ActiveRecord 类的元数据对象
	 *
	 * @static
	 *
	 * @return QDB_ActiveRecord_Meta
	 */
	static function meta()
	{
		return QDB_ActiveRecord_Meta::instance(__CLASS__);
	}


/* ------------------ 以上是自动生成的代码，不能修改 ------------------ */
	/**
	 * 更新采购单预计产品信息
	 * @param $item_new 新产品item信息
	 * @param $purchase_order_id 采购单id
	 */
	static function updateBudget($item_new, $purchase_order_id)
	{
		$item_in_db = Purchase_Order_Item::find('purchase_order_id=?', $purchase_order_id)->asArray()->getAll();
		$item_old = array();
		$purchase_order = Purchase_Order::find('id=?', $purchase_order_id)->asArray()->getOne();
		$warehouse_id = $purchase_order['warehouse_id'];
		foreach ($item_in_db as $iid)
		{
			$item_old[$iid['id']] = $iid;
		}
		$item_create = array_diff_key($item_new, $item_old);
		$item_del = array_diff_key($item_old, $item_new);
		$item_update = array_diff_key($item_new, $item_create);
		foreach ($item_create as $ic)
		{
			$item = new Purchase_Order_Item();
			$item->purchase_order_id = $purchase_order_id;
			$item->product_basic_id = $ic['product_basic_id'];
			$item->budget_quantity = $ic['budget_quantity'];
			$item->budget_price = $ic['budget_price'];
			$item->budget_provider_id = $ic['budget_provider_id'];
			$item->notes = $ic['notes'];
			$item->reason = $ic['reason'];
			$item->save();
			Product_Warehouse::purchaseBudgetQuantityIncrease(0, $ic['product_basic_id'], $warehouse_id, $ic['budget_quantity']);
		}
		foreach ($item_del as $id)
		{
			Product_Warehouse::purchaseBudgetQuantityDecrease(0, $id['product_basic_id'], $warehouse_id, $id['budget_quantity']);
			QDB::getConn()->execute('delete from purchase_order_item where id=' . $id['id']);
		}
		foreach ($item_update as $key => $iu)
		{
			$item = Purchase_Order_Item::find('id=?', $key)->getOne();
			$old_budget_quantity = $item['budget_quantity'];
			$item->product_basic_id = $iu['product_basic_id'];
			$item->budget_quantity = $iu['budget_quantity'];
			$item->budget_price = $iu['budget_price'];
			$item->budget_provider_id = $iu['budget_provider_id'];
			$item->notes = $iu['notes'];
			$item->reason = $iu['reason'];
			$item->save();
			Product_Warehouse::purchaseBudgetQuantityDecrease(0, $iu['product_basic_id'], $warehouse_id, $old_budget_quantity);
			Product_Warehouse::purchaseBudgetQuantityIncrease(0, $iu['product_basic_id'], $warehouse_id, $iu['budget_quantity']);
		}
		return array('ack' => SUCCESS, 'message' => '');
	}
	
	/**
	 * 更新采购单实际采购产品信息
	 * @param $item 产品item信息
	 * @param $purchase_order_id 采购单id
	 * @param $type 控制仓库和采购更新Item数据信息，为true时即采购更新，为false时即仓库更新
	 */
	static function updateActual($item, $purchase_order_id, $type=false)
	{
		$judge = Purchase_Order_Item::judgeUpdateActual($item, $purchase_order_id, $type);
		if ($judge['ack'] == SUCCESS)
		{
			$purchase_order = Purchase_Order::find('id=?', $purchase_order_id)->asArray()->getOne();
			$purchase_order_status = array(
				Q::ini('custom_flag/purchase_order_status/arrived/value'),
				Q::ini('custom_flag/purchase_order_status/partial_storaged/value')
			);
			$message = array();
			foreach ($item as $id => $i)
			{
				$purchase_order_item = Purchase_Order_Item::find('id=? and purchase_order_id=?', $id, $purchase_order_id)->getOne();
				if ($purchase_order_item['id'])
				{
					$product = Product_Basic::find('id=?', $purchase_order_item['product_basic_id'])->asArray()->getOne();
					if ($purchase_order_item['budget_quantity'] >= $i['actual_quantity'])
					{
						if ($purchase_order_item['audit_flag'] == Q::ini('custom_flag/purchase_order_item_audit_flag/unaudited/value'))
						{
							if (in_array($purchase_order['status'], $purchase_order_status))
							{
								Product_Warehouse::purchaseActualQuantityDecrease(0, $purchase_order_item['product_basic_id'], $purchase_order['warehouse_id'], (int)$purchase_order_item['actual_quantity']);
								Product_Warehouse::purchaseActualQuantityIncrease(0, $purchase_order_item['product_basic_id'], $purchase_order['warehouse_id'], $i['actual_quantity']);
							}
							Product_Warehouse::purchaseQuantityDecrease(0, $purchase_order_item['product_basic_id'], $purchase_order['warehouse_id'], (int)$purchase_order_item['actual_quantity']);
							if ($type)
							{
								$purchase_order_item->actual_price = isset($i['actual_price']) ? $i['actual_price'] : $purchase_order_item['actual_price'];
								$purchase_order_item->actual_provider_id = isset($i['actual_provider_id']) ? $i['actual_provider_id'] : $purchase_order_item['actual_provider_id'];
								$purchase_order_item->notes = isset($i['notes']) ? $i['notes'] : $purchase_order_item['notes'];
							}
							$purchase_order_item->actual_quantity = isset($i['actual_quantity']) ? $i['actual_quantity'] : $purchase_order_item['actual_quantity'];
							$purchase_order_item->save();
							Product_Warehouse::purchaseQuantityIncrease(0, $purchase_order_item['product_basic_id'], $purchase_order['warehouse_id'], $purchase_order_item['actual_quantity']);
						}
					}
					else
					{
						$message[] = $product['number'] . '：实际数不能大于预计数！';
					}
				}
			}
			if ($message)
			{
				return array('ack' => PARTIAL_FAILURE, 'message' => implode("\n", $message));
			}
			else
			{
				return array('ack' => SUCCESS, 'message' => '');
			}
		}
		else
		{
			return array('ack' => $judge['ack'], 'message' => $judge['message']);
		}
	}

	/**
	 * 判断周期结款采购单的供应商是否一致
	 * @param $order 订单信息
	 */
	static function judgeUpdateActual($item, $purchase_order_id, $type)
	{
		$purchase_order = Purchase_Order::find('id=?', $purchase_order_id)->asArray()->getOne();
		if ($purchase_order)
		{
			if ($purchase_order['payment_type'] == Q::ini('custom_flag/purchase_order_payment_type/period/value'))
			{
				if ($type)
				{
					$res = array_column($item, 'actual_provider_id');
					if (count(array_unique($res)) == 1)
					{
						return array('ack' => SUCCESS, 'message' => '');
					}
					else
					{
						return array('ack' => FAILURE, 'message' => '周期结款采购单供应商需相同！请检查采购单供应商');
					}
				}
				else
				{
					return array('ack' => SUCCESS, 'message' => '');
				}
			}
			else
			{
				return array('ack' => SUCCESS, 'message' => '');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '采购单不存在，ID=' . $purchase_order['id']);
		}
		
	}
	
	/**
	 * 更新采购退货单信息
	 * @param $item_new 产品item信息
	 * @param $purchase_drawback_id 采购退货单id
	 */
	static function updateDrawback($item_new, $purchase_drawback_id)
	{
		$purchase_drawback = Purchase_Order::find('id=?', $purchase_drawback_id)->asArray()->getOne();
		$item_in_db = Purchase_Order_Item::find('purchase_order_id=?', $purchase_drawback_id)->asArray()->getAll();
		$item_old = array();
		foreach ($item_in_db as $iid)
		{
			$item_old[$iid['id']] = $iid;
		}
		$item_create = array_diff_key($item_new, $item_old);
		$item_del = array_diff_key($item_old, $item_new);
		$item_update = array_diff_key($item_new, $item_create);
		foreach ($item_create as $ic)
		{
			$item = new Purchase_Order_Item();
			$item->purchase_order_id = $purchase_drawback_id;
			$item->product_basic_id = $ic['product_basic_id'];
			$item->actual_quantity = $ic['actual_quantity'];
			$item->actual_price = $ic['actual_price'];
			$item->actual_provider_id = $ic['actual_provider_id'];
			$item->notes = $ic['notes'];
			$item->save();
			Product_Warehouse::availableQuantityDecrease(0, $ic['product_basic_id'], $purchase_drawback['warehouse_id'], $ic['actual_quantity']);
		}
		foreach ($item_del as $id)
		{
			Product_Warehouse::availableQuantityIncrease(0, $id['product_basic_id'], $purchase_drawback['warehouse_id'], $id['actual_quantity']);
			Purchase_Order_Item::meta()->deleteWhere('id=?', $id['id']);
		}
		foreach ($item_update as $key => $iu)
		{
			$item = Purchase_Order_Item::find('id=?', $key)->getOne();
			$old_actual_quantity = $item['actual_quantity'];
			$item->product_basic_id = $iu['product_basic_id'];
			$item->actual_quantity = $iu['actual_quantity'];
			$item->actual_price = $iu['actual_price'];
			$item->actual_provider_id = $iu['actual_provider_id'];
			$item->notes = $iu['notes'];
			$item->save();
			Product_Warehouse::availableQuantityDecrease(0, $iu['product_basic_id'], $purchase_drawback['warehouse_id'], $iu['actual_quantity']);
			Product_Warehouse::availableQuantityIncrease(0, $iu['product_basic_id'], $purchase_drawback['warehouse_id'], $old_actual_quantity);
		}
		return array('ack' => SUCCESS, 'message' => '');
	}
	
	/**
	 * 删除采购单item并更新产品预计数量
	 * @param $purchase_order_id 采购单id
	 */
	static function del($purchase_order_id)
	{
		$purchase_order = Purchase_Order::find('id=?', $purchase_order_id)->asArray()->getOne();
		$item = Purchase_Order_Item::find('purchase_order_id=?', $purchase_order_id)->asArray()->getAll();
		foreach ($item as $i)
		{
			Product_Warehouse::purchaseBudgetQuantityDecrease(0, $i['product_basic_id'], $purchase_order['warehouse_id'], $i['budget_quantity']);
		}
		Purchase_Order_Item::meta()->deleteWhere('purchase_order_id=?', $purchase_order_id);
	}
	
	/**
	 * 删除采购退货单item并更新可用
	 * @param $drawback_id 采购退货单id
	 */
	static function delDrawback($drawback_id)
	{
		$drawback = Purchase_Order::find('id=?', $drawback_id)->asArray()->getOne();
		$item = Purchase_Order_Item::find('purchase_order_id=?', $drawback_id)->asArray()->getAll();
		foreach ($item as $i)
		{
			Product_Warehouse::availableQuantityIncrease(0, $i['product_basic_id'], $drawback['warehouse_id'], $i['actual_quantity']);
		}
		Purchase_Order_Item::meta()->deleteWhere('purchase_order_id=?', $drawback_id);
	}
}